package cn.edu.jxau.core.service;


import cn.edu.jxau.core.exception.ServiceException;
import cn.edu.jxau.core.process.spectrumutil.AlgorithmUtils;
import cn.edu.jxau.core.process.spectrumutil.GetSpectrum;
import cn.edu.jxau.core.util.DateUtils;
import cn.edu.jxau.core.util.SerializaObject;
import cn.edu.jxau.core.vo.Point;
import cn.edu.jxau.core.vo.SpectrumFile;
import cn.edu.jxau.framework.dao.core.Session;
import cn.edu.jxau.framework.dao.core.sqlSessionFactory;
import cn.edu.jxau.framework.dao.exception.ConfigurationException;
import com.alibaba.fastjson.JSONArray;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 算法业务
 *
 * @author 巫发萍
 * spectrum3
 * 2017年8月23日
 */
public class AlgorithmService extends ServiceSupport {
    private static Logger logger = LoggerFactory.getLogger(AlgorithmService.class);        //日志

    public AlgorithmService() {
    }

    public AlgorithmService(String view, Map<String, Object[]> params, Map<String, Object> data) throws ServiceException {
        /**
         * view service.xml中的name和视图对应
         * params request入口的参数数组
         * data 返回给Servlet的出口参数
         */
        super(view, params, data);
        execute(view, params, data); // 执行业务
    }

    /**
     * 预处理算法
     *
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     * @return 执行情况，和service.xml的result节点的name属性对应，代表转发页面
     * @author 巫发萍
     */
    @SuppressWarnings({"unused", "unchecked", "rawtypes"})
    protected void pretreatmentAlgorithm(Map<String, Object[]> params, Map<String, Object> data)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
        Map<String, Object> paramSpectrum = new HashMap<String, Object>();    //封装传递给数据库的参数,用于光谱查询
        Map<String, Object> paramAlgorithm = new HashMap<String, Object>();    //封装传递给数据库的参数，用于算法查询
        List<HashMap<String, Object>> datasSpectrum = new ArrayList<>();    //接收数据库返回回来的 ,用于光谱查询
        List<HashMap<String, Object>> datasAlgorithm = new ArrayList<>();    //接收数据库返回回来的 用于算法查询

        String spectrumFileUrl = null;        //光谱真实路径
        String algorithmRealPath = null;     //算法真实路径


        String algorithmID = getParamStringValue(params, "algorithmID", 0);
        String spectrumID = getParamStringValue(params, "spectrumID", 0);

        Session session = null;
        //查询数据库
        try {
            paramSpectrum.put("spectrumID", spectrumID);
            paramAlgorithm.put("algorithmID", algorithmID);
             session = sqlSessionFactory.getInstance().getSession();

            session.execute("wfpquerySpectrum", paramSpectrum, datasSpectrum);
            spectrumFileUrl = (String) datasSpectrum.get(0).get("spectrumFileUrl");

            session.execute("wfpqueryAlgorithm", paramAlgorithm, datasAlgorithm);
            algorithmRealPath = (String) datasAlgorithm.get(0).get("algorithmRealPath");
        } catch (Exception e) {
            logger.error("算法业务中预处理方法抛出异常");
            e.printStackTrace();
        }finally {
        	//释放连接
        	session.releaseConnection();
		}

        System.out.println(spectrumFileUrl);
        System.out.println(algorithmRealPath);

        // 在本地找到光谱文件
        SpectrumFile spectrumfile = GetSpectrum.parcelagle(spectrumFileUrl);

       /* try (
               FileReader fr = new FileReader(spectrumFileUrl)) {
            BufferedReader br = new BufferedReader(fr);
            String s = null;
            String readline = " ";
            while ((s = br.readLine()) != null) {
                readline = readline + s;
            }
            JSONObject spectrumjson = JSON.parseObject(readline);
            points = spectrumjson.getJSONArray("points");

            System.out.println(points);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/


        JSONArray pointsPretreatment = AlgorithmUtils.useJar2PrementSpectrum(algorithmRealPath, spectrumfile,false);

        // 添加光谱进数据库
        List<Point> pretreatmentPoints = new ArrayList<>();
        for (int i = 0, len = pointsPretreatment.size(); i < len; i++) {
            pretreatmentPoints.add(pointsPretreatment.getJSONObject(i).toJavaObject(Point.class));
        }
        //处理后的数据
        spectrumfile.setPoints(pretreatmentPoints);
        //重新序列化写入数据
        spectrumfile = SerializaObject.writeObject(spectrumfile);
    }



    /**
     * 分析算法
     *
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     */
    @SuppressWarnings("unused")
    private String analyzeAlgorithm(Map<String, Object[]> params, Map<String, Object> data) {
        return null;
    }

    /**
     * 查询算法
     *
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     * @author 巫发萍
     */
    @SuppressWarnings("unused")
    private void getAlgorithm(Map<String, Object[]> params, Map<String, Object> data) {
    	final String DIRMSG="一共查询到0条记录";
        Map<String, Object> paramAlgorithm = new HashMap<String, Object>();    //封装传递给数据库的参数，用于算法查询
        List<HashMap<String, Object>> datasAlgorithm = new ArrayList<>();    //接收数据库返回回来的 用于算法查询
        Session session = null;
		try {
			session = sqlSessionFactory.getInstance().getSession();
	        String algorithmID = getParamStringValue(params, "algorithmID", 0);
	        if(algorithmID!=null){
	        	paramAlgorithm.put("algorithmID", algorithmID);
	        	paramAlgorithm.put("isDelete", 0);
				session.execute("wfpqueryAlgorithm", paramAlgorithm, datasAlgorithm);

				data.put("datasAlgorithm", datasAlgorithm);
				data.put("result", SUCCESS);
	
	        }else{
		        //获取数据
		        paramAlgorithm.put("fileId", getParamStringValue(params, "fileId", 0));
		        paramAlgorithm.put("isDelete", 0);
				session.execute("wfpqueryAlgorithmByfileID", paramAlgorithm, datasAlgorithm);
				if(datasAlgorithm.isEmpty()){
					data.put("fileStatus", "0");
					data.put("fileEmpty", DIRMSG);
					data.put("result", "success");
				}else{
					data.put("fileStatus", "1");
					data.put("datasAlgorithm", datasAlgorithm);
					data.put("result", "success");
				}
	        }
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			session.releaseConnection();
		}
        
    }

    /**
     * 上传算法文件
     *
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     * @author 巫发萍
     */
    @SuppressWarnings("unused")
    private void updateAlgorithm(Map<String, Object[]> params, Map<String, Object> data) {
    
    	Map<String, Object> paramAlgorithm = new HashMap<String, Object>();    //封装传递给数据库的参数，用于算法查询
    	Map<String, Object> paramAlgorithmSelect = new HashMap<String, Object>();    //封装传递给数据库的参数，用于算法查询
        List<HashMap<String, Object>> datasAlgorithm = new ArrayList<>();    //接收数据库返回回来的 用于更新查询
        
        //获取数据
        paramAlgorithm.put("algorithmID", getParamStringValue(params, "algorithmID", 0));
        paramAlgorithm.put("algorithmName", getParamStringValue(params, "algorithmName", 0));
        paramAlgorithm.put("algorithmSort", getParamStringValue(params, "algorithmSort", 0));
        paramAlgorithm.put("algorithmVesion", getParamStringValue(params, "algorithmVesion", 0));
        paramAlgorithm.put("algorithmDscription", getParamStringValue(params, "algorithmDscription", 0));
        paramAlgorithm.put("algorithmLanguag", getParamStringValue(params, "algorithmLanguag", 0));
        paramAlgorithm.put("id", getParamStringValue(params, "id1", 0));
        
        paramAlgorithmSelect.put("fileId", getParamStringValue(params, "fileID", 0));
        
        Session session = null;
		try {
			session = sqlSessionFactory.getInstance().getSession();
			Boolean aa = session.execute("wfpupdataAlgorithm", paramAlgorithm, datasAlgorithm);
			session.execute("wfpqueryAlgorithmByfileID", paramAlgorithmSelect, datasAlgorithm);
			data.put("datasAlgorithm", datasAlgorithm);
			data.put("result", SUCCESS);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			session.releaseConnection();
		}
        
    }

    /**
     * 下载算法文件
     *
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     * @author 巫发萍
     */
    private void downAlgorithm(Map<String, Object[]> params, Map<String, Object> data) {
	   	Map<String, Object> paramAlgorithm = new HashMap<String, Object>();    //封装传递给数据库的参数，用于算法查询
	    List<HashMap<String, Object>> datasAlgorithm = new ArrayList<>();    //接收数据库返回回来的 用于算法查询
	    
	    paramAlgorithm.put("algorithmID", getParamStringValue(params, "algorithmID", 0));
	    paramAlgorithm.put("isDelete", 0);
	    Session session = null;
	    String target = null;
	    try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("wfpqueryAlgorithm", paramAlgorithm, datasAlgorithm);
			System.out.println(datasAlgorithm.toString());
			target = (String) datasAlgorithm.get(0).get("algorithmRealPath");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    File file = new File(target);

        data.put("file", file);   
        System.out.println(file.exists());
        System.out.println(file.getAbsolutePath());
        if (file.exists()){
            data.put("result", SUCCESS);
        }
    }
    /**
     * 删除算法
     *
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     * @author 巫发萍
     */
    @SuppressWarnings("unused")
    private void deleteAlgorithm(Map<String, Object[]> params, Map<String, Object> data) {
    	 Map<String, Object> paramAlgorithm = new HashMap<String, Object>();    //封装传递给数据库的参数，用于算法查询
         List<HashMap<String, Object>> datasAlgorithm = new ArrayList<>();    //接收数据库返回回来的 用于算法查询
         paramAlgorithm.put("id", getParamStringValue(params, "algorithmID", 0));
         paramAlgorithm.put("isDelete", 1);
         Session session = null;
         
         try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("wfpdeleteAlgorithm", paramAlgorithm, datasAlgorithm);
			data.put("result", SUCCESS);
         } catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			session.releaseConnection();
		}
         
    }

    /**
     * 添加算法
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     * @throws ConfigurationException
     * @author 巫发萍
     */
    @SuppressWarnings("unused")
    private void addAlgorithm(Map<String, Object[]> params, Map<String, Object> data) throws ConfigurationException {
        Map<String, Object> paramAlgorithm = new HashMap<String, Object>();    //封装传递给数据库的参数，用于算法查询
        List<HashMap<String, Object>> datasAlgorithm = new ArrayList<>();    //接收数据库返回回来的 用于算法查询
        File[] files = (File[]) params.get("file");
        if(files!=null){
	        File spectrumFile = null;
	        for (File file : files) {
	            spectrumFile = file;
	        }
	        //获取数据
	        paramAlgorithm.put("algorithmID", 20151712);
	        paramAlgorithm.put("algorithmName", getParamStringValue(params, "algorithmName", 0));
	        paramAlgorithm.put("algorithmSort", getParamStringValue(params, "algorithmSort", 0));
	        paramAlgorithm.put("algorithmUploadtime", DateUtils.getNowTime());
	        paramAlgorithm.put("algorithmVesion", getParamStringValue(params, "algorithmVesion", 0));
	        paramAlgorithm.put("algorithmDscription", getParamStringValue(params, "algorithmDscription", 0));
	        paramAlgorithm.put("algorithmLanguag", "java");
	        paramAlgorithm.put("algorithmRealPath", spectrumFile.getAbsolutePath());
	        paramAlgorithm.put("fileID", getParamStringValue(params, "fileID", 0));
	        //添加数据库
	        try {
	            Session session = sqlSessionFactory.getInstance().getSession();
	            Boolean succes = session.execute("wfpaddAlgorithm", paramAlgorithm, datasAlgorithm);
	            data.put("result", SUCCESS);
	        } catch (ClassNotFoundException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (DocumentException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
        }else{
        	data.put("result", FAILED);
        }


    }

    /**
     * 查询算法文件夹
     * @author 巫发萍
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     */
    @SuppressWarnings("unused")
	private void getAlgorithmDir(Map<String, Object[]> params, Map<String, Object> data) {
    	final String DIRMSG="一共查询到0条记录";
    	Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        Map<String,Object> map=new HashMap<String, Object>();//存放光谱类型
        List<HashMap<String, Object>> datasAlgorithmDir = new ArrayList();  // 用来接收数据库返回回来的数据
        
        Pattern pattern = Pattern.compile("[0-9]*");    //正则判断字符串是否是数字
        String userId=getParamStringValue(params,"userID",0);
        Matcher isNum = pattern.matcher( userId);
        //判断field是否为空或是否是数字
        if(null!=userId&&isNum.matches()){
            int UserID=Integer.parseInt(userId);
            param.put("UserID", UserID);
        }else{
            return;
        }

        Session session = null;
        try {
            session = sqlSessionFactory.getInstance().getSession();
            session.execute("wfpqueryAlgorithmDir", param, datasAlgorithmDir);
            if(datasAlgorithmDir==null&&datasAlgorithmDir.isEmpty()){
                data.put("dirStatus","0");
                data.put("dirEmpty",DIRMSG);
                data.put("result", SUCCESS);
            }else{
                data.put("dirStatus","1");
                data.put("algorithmDir",datasAlgorithmDir);
                data.put("result", SUCCESS);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }finally {
            //释放连接
          session.releaseConnection();
		}
    }
    
    /**
     * 添加算法文件夹
     * @author 巫发萍
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     */
    private void addAlgorithmDir(Map<String, Object[]> params, Map<String, Object> data){
    	Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datasAlgorithmDir = new ArrayList();  // 用来接收数据库返回回来的数据
        
        Pattern pattern = Pattern.compile("[0-9]*");		//正则判断字符串是否是数字
        String userId=getParamStringValue(params,"userID",0);
        
        Matcher isNum = pattern.matcher( userId);
        //判断field是否为空或是否是数字
        if(null!=userId&&isNum.matches()){
            int UserID=Integer.parseInt(userId);
            param.put("UserID", UserID);
        }else{
            return;
        }
        //判断文件名是否合法
            String fileName=getParamStringValue(params,"fileName",0);
            if(fileName.length()<16&&fileName.length()>1){
                param.put("fileName",fileName);
            }else{
                data.put("fileNameError","您输入的名字不合法");
              return;
            }
        //判断params是否为空或是否为null,若不为空则插入数据库
        Session session = null;
        try {
        	param.put("typeID", "1");
            session = sqlSessionFactory.getInstance().getSession();
            session.execute("wfpinsertAlgorithmDir", param, datasAlgorithmDir);
            data.put("addsuccess","添加成功");
            data.put("result",SUCCESS);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }finally {
            session.releaseConnection();
        }
    }
    
    /**
     * 删除算法文件夹
     * @author 巫发萍
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     */
    private void deleteAlgorithmDir(Map<String, Object[]> params, Map<String, Object> data){
    	Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
    	Map<String, Object> paramAlgorithmdelete = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datasAlgorithmDir = new ArrayList();  // 用来接收数据库返回回来的数据
        List<HashMap<String, Object>> datasAlgorithmDirAlgorithm = new ArrayList();  // 用来接收数据库返回回来的数据
        List<HashMap<String, Object>> datasAlgorithmdelete = new ArrayList();  // 用来接收数据库返回回来的数据
        
        Pattern pattern = Pattern.compile("[0-9]*");    //正则判断字符串是否是数字
        String userId=getParamStringValue(params,"userID",0);
        Matcher isNum = pattern.matcher( userId);
        //判断field是否为空或是否是数字
        if(null!=userId&&isNum.matches()){
            int UserID=Integer.parseInt(userId);
            param.put("UserID", UserID);
            
        }else{
            return;
        }
        
        String dirID=getParamStringValue(params,"dirID",0);
        param.put("dirID", dirID);
        paramAlgorithmdelete.put("dirID", dirID);

        Session session = null;
        
        try {
			session = sqlSessionFactory.getInstance().getSession();
			//查询该文件夹下是否有算法文件
			session.execute("wfpqueryAlgorithmByDir", param, datasAlgorithmDirAlgorithm);
			System.out.println(datasAlgorithmDirAlgorithm);
			if(datasAlgorithmDirAlgorithm!=null){
				for(HashMap datasAlgorithmDirAlgorithm1 : datasAlgorithmDirAlgorithm){
					int algorithmID = Integer.parseInt(datasAlgorithmDirAlgorithm1.get("algorithmID").toString());
					paramAlgorithmdelete.put("algorithmID", algorithmID);
					session.execute("wfpdeleteAlgorithm", paramAlgorithmdelete, datasAlgorithmdelete);
				}
			}
			
			session.execute("wfpdeleteAlgorithmDir", param, datasAlgorithmDir);
		
            data.put("result",SUCCESS);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			session.releaseConnection();
		}
    }
    
    /**
     * 对算法文件夹进行重命名
     * @author 巫发萍
     * @param params：存储边界类的数据
     * @param data：出口参数，回送至web层
     */
    private void renameAlgorithmDir(Map<String, Object[]> params, Map<String, Object> data){
    	Map<String, Object> paramAlgorithmDir = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datasAlgorithmDir = new ArrayList();  // 用来接收数据库返回回来的数据
        String newName = getParamStringValue(params,"newName",0);
        if(newName !=null){
        	paramAlgorithmDir.put("newName", newName);
            paramAlgorithmDir.put("favoriteid", getParamStringValue(params,"favoriteid",0));
            paramAlgorithmDir.put("userID", getParamStringValue(params,"userID",0));
            Session session = null;
        }else{
        	data.put("result",FAILED);
        }
        
        Session session = null; 
        try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("wfpupdateAlgorithmDir", paramAlgorithmDir, datasAlgorithmDir);
			data.put("result",SUCCESS);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			session.releaseConnection();
		}
    }

}
